package com.quanquan.store.listeners;

import com.quanquan.store.dao.CouponCacheDao;
import com.quanquan.store.entity.Coupon;
import com.quanquan.store.entity.Order;
import com.quanquan.store.repository.CouponRepository;
import com.quanquan.store.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class KeyExpireListener extends KeyExpirationEventMessageListener {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CouponRepository couponRepository;
    @Autowired
    private CouponCacheDao couponCacheDao;


    public KeyExpireListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 去世的key
        String key = message.toString();
        // 这里处理活动数据变化的逻辑
        if (key.contains("couponOrder-")) {
            String couponOrderNum = key.split("-")[1];
            Order order = orderRepository.findByOrderNum(couponOrderNum);
            // 如果订单过期，返回券的库存
            String s = couponCacheDao.get(order.getCouponId());
            if (s != null) {
                Integer integer = Integer.valueOf(s);
                int couponRemainTotal = integer + order.getCount();
                couponCacheDao.save(order.getCouponId(), Integer.toString(couponRemainTotal));
            }
            Coupon byCouponId = couponRepository.findByCouponId(order.getCouponId());
            if (byCouponId != null && byCouponId.getSumType() == 0) {
                byCouponId.setCount(byCouponId.getCount() + order.getCount());
                couponRepository.saveAndFlush(byCouponId);
            }
        }
    }


}
